package main

import (
	"encoding/csv"
	"encoding/json"
	"io/ioutil"
	"math"
	"sort"
	"strings"

	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/uuid"
	"github.com/jmoiron/sqlx"
	"io"
	"log"
	"math/rand"
	"os"
	"strconv"
	"time"
)
var (
	database     *sqlx.DB //mysql连接对象//
	userPool []UserData
	userOffset int
	timePool []int
	mainConf *MainConfig
	trandata 	chan UserData
)

//把字母转为数字
func getNumByLetter(letter string) int{
	result := 0
	for i :=0; i < len(letter); i++ {
		temp := letter[i]
		if temp <'A' || temp > 'Z' {
			return result - 1
		}
		num := int(temp - 'A' + 1 )
		result = result * 26 + num
		//fmt.Println("num", result)
	}
	return result - 1
}

//局数等到随机的分数
func randomScore(score, count, min, max int)[]int{
	var retlist []int
	score -= min*count
	for count > 1 {
		maxRemain := score/count*2
		if maxRemain > max {
			maxRemain = max
		}
		if maxRemain < min {
			maxRemain = min + 1
		}
		//fmt.Println("maxRemain", maxRemain, score, count, min)
		ret := RandInts(0, maxRemain - min)
		score -= ret
		count --
		retlist = append(retlist, ret + min)
	}
	retlist = append(retlist, score + min)
	return retlist
}
func RandInts(min, max int) int {
	rr := rand.New(rand.NewSource(time.Now().UnixNano() * rand.Int63n(9999)))
	//fmt.Println(min, max, max - min + 1)
	return rr.Intn(max - min + 1) + min
}

//对局id
func CreateRefId(playType int) string {
	serverId := RandInts(1,3)
	return strconv.Itoa(int(serverId)) + "_" + strconv.Itoa(int(playType)) + "_" + uuid.New().String()
}


//连接mysql
func initMysql() {
	fmt.Printf("StartDB...")

	var err error
	//Log.Printf("mysql config, host:%s, name:%s, name:%s", MysqlConfigViper_.GetString("host"), MysqlConfigViper_.GetString("name"), MysqlConfigViper_.GetString("username"))
	connStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true&loc=Local&charset=utf8",
		"root", "f3bc7ec833F98e491939e74a90d875", "120.76.201.244:3306", "indiaGame")
	database, err = sqlx.Connect("mysql", connStr)
	if err != nil {
		panic(err)
	}
	database.DB.SetMaxOpenConns(500)
	database.DB.SetMaxIdleConns(100)
	database.DB.SetConnMaxLifetime(time.Second * 0)
	fmt.Printf("The Db is: %v \n", database)
}
func mysqlReadOne(){
	dest := &UserData{}
	sql := "select * from india_user where playType=? limit ?"
	err := database.Get(dest, sql, 113, 1)
	if err != nil {
		fmt.Printf("DBCache.Get failed, sql:%s, dest:%+v, err:%+v", sql, dest, err)
		return
	}
	fmt.Println()
	fmt.Println("select succ:", dest)
}
//查户信息
func queryUser(createTime string, createTime2 string, playType int, limit int, offset int) []UserData{
	sql := fmt.Sprintf("select * from india_user where playType=%d and regTime < '%s' and regTime > '%s' limit %d offset %d ", playType, createTime, createTime2, limit, offset)
	results, err := database.Query(sql)
	//fmt.Println("sql ",sql)
	if err != nil {
		fmt.Println("sql ",sql)
		panic(err.Error())
	}
	userArr := []UserData{}
	for results.Next() {
		var data UserData
		err = results.Scan(&data.Id, &data.RegTime, &data.Region, &data.PlayType)
		if err != nil {
			//panic(err.Error())
			fmt.Println("ERROR scan ", err)
			continue
		}
		userArr = append(userArr, data)
	}
	return userArr
}

//取用户信息
func queryUser2(playType int, limit int, offset int, back func(*UserData)){
	sql := fmt.Sprintf("select * from india_user where playType=%d limit %d offset %d", playType, limit, offset)
	fmt.Println("sql", sql)
	results, err := database.Query(sql)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	for results.Next() {
		var data UserData
		err = results.Scan(&data.Id, &data.RegTime, &data.Region, &data.PlayType)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		del := (RandInts(0,8) - data.Id%9 + 9)%9
		if del < 4 {
			back(&data)
		}
	}
}

//取用户信息
/*
uid 注册时间要<对局创建时间
uid 使用多少次
 */
func getUser(date int64) UserData{
	dateStr := time.Unix(int64(date - 180), 0).Format("2006-01-02 15:04:05")
	date2Str := time.Unix(int64(date - 55*86400), 0).Format("2006-01-02 15:04:05")
	if len(userPool) == 0 {
		limit := RandInts(300, 3000)
		//limit := offset * RandInts(2,10)
		userPool = queryUser(dateStr, date2Str, 113, limit, userOffset)
		userOffset =  RandInts(0, 200)
		//fmt.Println("userOffset", userOffset)
		for {
			if len(userPool) == 0 {
				userOffset = userOffset - 100
				if userOffset < 0 {
					userOffset = 0
					limit = 100
				}
			}else {
				break
			}
			userPool = queryUser(dateStr, date2Str,113, limit, userOffset)
			if userOffset == 0 {
				break
			}
		}
		//打乱数据
		for i := len(userPool) - 1; i > 0; i-- {
			num := rand.Intn(i + 1)
			userPool[i], userPool[num] = userPool[num], userPool[i]
		}
	}
	maxSize := len(userPool)
	for i := 0; i < maxSize; i++ {
		user := userPool[0]
		userPool = append(userPool[1:])
		maxSize = len(userPool)
		if user.RegTime.Unix() + 3*60 > int64(date) {
			//fmt.Println("___", user.RegTime.Unix() + 3*60, date)
			continue
		}
		return user
	}
	if len(userPool) == 0 {
		userPool = queryUser(dateStr, date2Str,113, 100, 0)
		//打乱数据
		for i := len(userPool) - 1; i > 0; i-- {
			num := rand.Intn(i + 1)
			userPool[i], userPool[num] = userPool[num], userPool[i]
		}
	}
	//fmt.Println("___date", len(userPool), date)
	return userPool[len(userPool) - 1]


}



func getTime(date string, num int) int {
	if len(timePool) == 0 {
		timePool = getTimeList(date, num)
	}
	timeNum := timePool[0]
	timePool = append(timePool[1:])
	//fmt.Println("getTime", time.Unix(int64(timeNum),0))
	//第一个用户注册时间 2019-12-04 00:05:24
	userRegTimeMin := 1575389124
	if timeNum < userRegTimeMin + 3*60 {
		timeNum = userRegTimeMin + RandInts(3*60, 10*60)
	}
	return timeNum
}

//写入数据库
func writeRummyData(data *RummyData) {
	sql := "insert into india_round_rummy(createdAt, uid, region, playType, playSubType, level, platformCommission, refId)" +
			"values(:createdAt, :uid, :region, :playType, :playSubType, :level, :platformCommission, :refId)"
	_, err := database.NamedExec(sql, data)
	if err != nil {
		fmt.Printf("writeRummyData ERROR sql:%v, err:%+v \n", sql, err)
		return
	}
	//fmt.Printf("writeRummyData success sql:%v \n", sql)
}

type RummyDataList []RummyData
func (r RummyDataList) Len() int {
	return len(r)
}
func (r RummyDataList) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
}
func (r RummyDataList) Less(i, j int) bool{
	return r[j].CreatedAt.Unix() < r[i].CreatedAt.Unix()
}

var totalCount int

func writeRummyDataList(dataList []RummyData) {
	if len(dataList) <= 0 {
		return
	}

	//按时间排序
	sort.Sort(sort.Reverse(RummyDataList(dataList)))
	startTime := time.Now()
	totalCount = totalCount + len(dataList)
	fmt.Println("writeRummyDataList dataList size ", len(dataList), startTime)
	for _, rummyData := range dataList {
		//fmt.Printf("rummyData:%v \n", rummyData)

			//data := getUser(rummyData.CreatedAt.Unix())

			//fmt.Printf("data:%v \n", data)
			//rummyData.Uid = data.Id
			//rummyData.Region = data.Region
			writeRummyData(&rummyData)

	}
	fmt.Printf("writeRummyDataList end size:%v, useTime:%vs \n", len(dataList), time.Now().Unix() - startTime.Unix())
	fmt.Println("totalCount:", totalCount)
}


type UserData struct {
	Id       int       `json:"id" db:"id"`
	RegTime  time.Time `json:"regTime" db:"regTime"`
	Region   string    `json:"region" db:"region"`
	PlayType int       `json:"playType" db:"playType"`
}

type RummyData struct {
	CreatedAt          time.Time `json:"createdAt" db:"createdAt"`
	Uid                int       `json:"uid" db:"uid"`
	Region             string    `json:"region" db:"region"`
	PlayType           int       `json:"playType" db:"playType"`
	PlaySubType        int       `json:"playSubType" db:"playSubType"`
	Level              float32   `json:"level" db:"level"`
	PlatformCommission float32   `json:"platformCommission" db:"platformCommission"`
	RefId              string    `json:"refId" db:"refId"`
}

func getRandTimeByWeight()int{
	timeweight := [...]int{85,66,52,43,33,22,11,15,20,25,28,30,38,40,38,55,60,65,63,68,71,75,70,66,75,80,85,90,100,90,80,75,66,68,74,66,88,80,95,88,90,100,100,100,80,70,75,80}
	for i := 1; i< 48; i++ {
		timeweight[i] += timeweight[i-1]
	}
	ret := RandInts(1, timeweight[47])
	dex := 0
	for i := 0; i< 48; i++ {
		if ret <= timeweight[i] {
			dex = i
			break
		}
	}
	return dex
}

//取随机时间
func getRandTime(date string) int{
	arr := strings.Split(date, "/")
	str := ""
	for _, v := range arr {
		if len(v) == 1 {
			v = "0" + v
		}
		str = str + "/" + v
	}
	str = strings.TrimLeft(str, "/")
	//fmt.Println("strDate", str)

	//随机时间
	timeObj, _ := time.Parse("2006/01/02", str)
	//fmt.Println("timeNum", timeObj, timeObj.Unix())
	timeNum := timeObj.Unix()
	min := getRandTimeByWeight()*1800
	ret := int(timeNum-8*3600) + RandInts(min, min+1800)
	return ret
}

//取一天的时间列表
func getTimeList(date string, num int) (timeList []int) {
	for i := 0; i < num; i++ {
		t := getRandTime(date)
		timeList = append(timeList, t)
	}
	sort.Ints(timeList)
	return timeList
}

//四舍五入取进度
func getPrecision(value float32, precision int) float32 {
	if precision <= 0 {
		operValue := float32(int32(value*1+0.5)) / float32(1)
		return operValue
	} else if precision == 1 {
		//取1位小数
		operValue := float32(int32(value*10+0.5)) / float32(10)
		return operValue
	} else if precision == 2 {
		//取2位小数
		operValue := float32(int32(value*100+0.5)) / float32(100)
		return operValue
	} else if precision == 3 {
		//取3位小数
		operValue := float32(int32(value*1000+0.5)) / float32(1000)
		return operValue
	} else {
		//取4位小数
		operValue := float32(int32(value*10000+0.5)) / float32(10000)
		return operValue
	}
}

func insertData()  {
	fmt.Println("insertData")
	//准备读取文件
	fileName := "data.csv"
	fs, err := os.Open(fileName)
	if err != nil {
		log.Fatalf("can not open the file, err is %+v", err)
	}
	defer fs.Close()
	//我需要用到的字段
	dataMap := map[string][]string{
		"0.05":    []string{"A", "H", "L", "K"}, //0.05
		"0.1":     []string{"A", "O", "S", "R"}, //0.1
		"0.25":    []string{"A", "V", "Z", "Y"}, //0.25
		"0.5":     []string{"A", "AC", "AG", "AF"}, //0.5
		"1":       []string{"A", "AJ", "AN", "AM"}, //1
		"2":       []string{"A", "AQ", "AU", "AT"}, //2
		"5":       []string{"A", "AX", "BB", "BA"}, //5
		"10":      []string{"A", "BE", "BI", "BH"}, //10
		"50":  []string{"A", "BL", "BN", "BM"}, //pool50
		"100": []string{"A", "BQ", "BS", "BR"}, //pool100
	}
	r := csv.NewReader(fs)

	//针对大文件，一行一行的读取文件

	//for i:=0; i<4; i++ {
	for i := 0; ; i++ {
		row, err := r.Read()
		if err != nil && err != io.EOF {
			log.Fatalf("can not read, err is %+v", err)
		}
		if err == io.EOF {
			break
		}
		if i < 2 {
			continue
		}
		fmt.Printf("[day: %v, %v] \n", i-1, row[0])

		rummyDataList := []RummyData{}
		dataArr := []string{}
		for roomType, letterArr := range dataMap {
			//fmt.Println("roomType", roomType)
			dataArr = []string{}
			for _, v := range letterArr {
				num := getNumByLetter(v)
				data := row[num]
				if data == "" {
					data = "0"
				}
				//fmt.Printf(" %v %+v ", v, data)
				dataArr = append(dataArr, data)
			}
			//fmt.Printf("%v \n", dataArr)
			/*取到字段生成数据
			表里的字段顺序是这样的：
			时间、用户ID、用户所在地、玩法、场次（桌球：入场费、rummy：底分、德州：小盲）、抽水金额、对局ID
			非pool50和pool100 单局最小分数2最大分数400
			pool50和pool100 单局最小人次1最大人次5

			dataArr -> 日期， 局数， 单局抽水， 总分
			*/
			//局数列表
			allScore, _ := strconv.Atoi(dataArr[3])
			count, _ := strconv.Atoi(dataArr[1])
			charge, _ := strconv.ParseFloat(dataArr[2],2)
			dataDate := dataArr[0]
			if count == 0 || allScore == 0 || dataDate == "" || charge <= 0 {
				continue
			}
			min := 2
			max := 400
			if roomType == "50" || roomType == "100" {
				min = 1
				max = 5
			}
			roundArr := randomScore(allScore, count, min, max)
			//fmt.Printf("playType:%v, allScore:%v, count:%v roundArr:%v \n",roomType, allScore, count, len(roundArr))

			for _, score := range roundArr {
				date := getTime(dataDate, count) //根据
				user := getUser(int64(date))
				uid := user.Id
				//playType := user.PlayType
				playSubType := 1
				if roomType == "50" || roomType == "100" {
					playSubType = 2
				}
				platformCommission := float64(score) * charge//
				platformCommission = float64(getPrecision(float32(platformCommission), 2))
				refId := CreateRefId(113)
				region := user.Region
				level, _ := strconv.ParseFloat(roomType, 2)

				rummyData := RummyData{
					time.Unix(int64(date), 0),
					uid,
					region,
					113,
					playSubType,
					float32(level),
					float32(platformCommission),
					refId,
				}
				rummyDataList = append(rummyDataList, rummyData)
			}
		}

		writeRummyDataList(rummyDataList)

	}

}

//配置结构
type MainConfig struct {
	CsvFile   string `json:"csvFile"`
	Ip string `json:"ip"`
	User string `json:"user"`
	Password string `json:"password"`
	DbName   string `json:"dbName"`
}

func readConf(fname string) (p *MainConfig, err error) {
	var (
		fp *os.File
		fcontent []byte
	)
	p = &MainConfig{}
	if fp, err = os.Open(fname); err != nil {
		fmt.Println("open error ", err)
		return
	}

	if fcontent, err = ioutil.ReadAll(fp); err != nil {
		fmt.Println("ReadAll error ", err)
		return
	}
	fmt.Println("fcontent", fcontent)
	if err = json.Unmarshal(fcontent, p); err != nil {
		fmt.Println("toml.Unmarshal error ", err)
		return
	}
	return
}



func testFunc(){
	//getNumByLetter("AA")
	//res := randomScore(5732,0, 2, 400)
	//fmt.Println("res",res)
	//arr := queryUser(113, 1, 1)
	//fmt.Println("arr", arr)
	//user := getUser()
	//fmt.Println(user)
	//user = getUser()
	//fmt.Println(user)
	//user = getUser()
	//fmt.Println(user)
	//
	//
	//date, _:= time.Parse("2006/01/02", "2019/12/2") //根据
	//fmt.Println("date", date, date.Unix())

	//
	//timeNum := getRandTime("2019/12/4")
	//fmt.Println("timeNum ", timeNum, time.Unix(int64(timeNum),0))

	//timeList := getTimeList("2019/12/4", 174)
	//fmt.Println(len(timeList))
	//for i:=0; i<174; i++ {
	//	timeNum := timeList[0]
	//	timeList = append(timeList[1:])
	//	fmt.Println(time.Unix(int64(timeNum),0))
	//}
	//for _, v := range timeList {
	//	fmt.Println(time.Unix(int64(v),0))
	//}


	//data := RummyData{
	//	CreatedAt: time.Now(),
	//	Uid: 100,
	//	Region: "india",
	//	PlayType: 113,
	//	PlaySubType: 1,
	//	Level: 0.01,
	//	PlatformCommission: 1.2,
	//	RefId: "roomid2222",
	//
	//}
	//writeRummyData(&data)

	//var err error
	//mainConf, err = readConf("config.json")
	//fmt.Println(mainConf, err)
	//fmt.Println(mainConf.Ip)

	//count, err := strconv.Atoi("#DIV/0!")
	//fmt.Println(count, err)


}

func testGetData() {

	/*------------------------------------------------------钱包信息------------------------------------------------------*/
	type DayWithdrawItem struct {
		WithdrawTime time.Time `json:"withdrawTime"`         //该笔提现记录时间//
		Amount       float32   `json:"amount"`               //提现金额//
		Account      string    `json:"account" db:"account"` //提现账号，paytm电话，邮件或者bank account//
	}
	//常规优惠//
	type NormalDepositItem struct {
		Valid              int32     `json:"valid"`              //有效//
		NormalDepositCount int32     `json:"normalDepositCount"` //常规优惠阶段的充值次数//
		FinishTime         time.Time `json:"finishTime"`         //该优惠完成时间//
	}
	//定制优惠//
	type CustomDepositItem struct {
		Valid          int32     `json:"valid"`                              //有效//
		Amount         int32     `json:"amount"`                             //档位金额，只有定制优惠有该金额//
		StartTime      time.Time `json:"startTime"`                          //该优惠开始时间//
		FinishTime     time.Time `json:"finishTime"`                         //该优惠完成时间//
		FreezeDuration int32     `json:"freezeDuration" db:"freezeDuration"` //冻结时间//
	}
	//节日优惠//
	type FestivalDepositItem struct {
		FinishTime     time.Time `json:"finishTime"`                         //该优惠完成时间//
		FreezeDuration int32     `json:"freezeDuration" db:"freezeDuration"` //冻结时间//
	}
	type WalletInfo struct {
		Uid              int32     `json:"uid" db:"uid"`                           //uid//
		WithdrawTime     time.Time `json:"withdrawTime"`                           //最近的提现时间//
		TotalDayWithdraw float32   `json:"totalDayWithdraw"`                       //今日提现总额//
		TotalDeposit     float32   `json:"totalDeposit" db:"totalDeposit"`         //累计充值//
		TotalWithdraw    float32   `json:"totalWithdraw" db:"totalWithdraw"`       //累计提现//
		MaxDepositAmount float32   `json:"maxDepositAmount" db:"maxDepositAmount"` //最大单笔充值金额//

		PigDeposit        float32 `json:"pigDeposit" db:"pigDeposit"`               //金猪存钱罐的金额//
		CommissionDeposit float32 `json:"commissionDeposit" db:"commissionDeposit"` //佣金储蓄//

		LastDepositMobile string `json:"lastDepositMobile" db:"lastDepositMobile"` //最近的充值paytm电话，邮箱账号或者电话//

		LastWithdrawMobile   string `json:"lastWithdrawMobile" db:"lastWithdrawMobile"`     //paytm钱包账号，用于paytm和paytm gift提现，没有加91//
		LastWithdrawBank     string `json:"lastWithdrawBank" db:"lastWithdrawBank"`         //银行账号，如果是paytm银行，可能是91mobile，也可能是mobile，都可以正常提现//
		LastWithdrawBankIFSC string `json:"lastWithdrawBankIFSC" db:"lastWithdrawBankIFSC"` //银行账号IFSC//
		Upi                  string `json:"upi" db:"upi"`                                   //upi账号//

		FavourNormal      int32  `json:"favourNormal" db:"favourNormal"`           //常规返利状态，0：还未开始，1：进行中，2：已结束//
		LastDepositAmount string `json:"lastDepositAmount" db:"lastDepositAmount"` //最近5次的充值金额//

		NormalDeposit   *NormalDepositItem   `json:"normalDeposit"`   //常规优惠//
		CustomDeposit   *CustomDepositItem   `json:"customDeposit"`   //定制优惠//
		FestivalDeposit *FestivalDepositItem `json:"festivalDeposit"` //节日优惠//

		DayList []*DayWithdrawItem `json:"dayList"`
	}
	walletInfo := &WalletInfo{}
	sql := "select * from walletInfo where uid=? limit 1"
	uid := 36611580
	err := database.Get(walletInfo, sql, uid)
	if err != nil && strings.Contains(err.Error(), "sql: no rows in result") {
		fmt.Println("err", err, walletInfo)
	}
}

func changeData() []int {
	/*
	1查总数
	2取差值
	3修改指定个数 +0.01 -0.01
	43494.29
	312882.97
	310970.13
	1694572.12
	4974217.49
	4916382.92
	3844869.93
	4580391.6
	11466688
	2150974.53
	1941801.7
	1927358.17

	 */
	//sql := fmt.Sprintf("SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-03-01' and createdAt < '2020-034-01' ", playType, createTime, createTime2, limit, offset)
	sqlArr := []string{
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-01-01' and createdAt < '2020-02-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-02-01' and createdAt < '2020-03-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-03-01' and createdAt < '2020-04-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-04-01' and createdAt < '2020-05-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-05-01' and createdAt < '2020-06-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-06-01' and createdAt < '2020-07-01'",

		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-07-01' and createdAt < '2020-08-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-08-01' and createdAt < '2020-09-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-09-01' and createdAt < '2020-10-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-10-01' and createdAt < '2020-11-01'",
		"SELECT sum(platformCommission) FROM india_round_rummy WHERE createdAt >= '2020-11-01' and createdAt < '2020-12-01'",

	}
	targetNumArr := []float64{
		312882.97,
		310970.13,
		1694572.12,
		4974217.49,
		4916382.92,
		3844869.93,
		4580391.6, //7
		11466688,
		2150974.53,
		1941801.7,
		1927358.17,
	}
	delayArr := []int{}
	for i, sql := range sqlArr {
		results, err := database.Query(sql)
		fmt.Println("sql ", sql)
		if err != nil {
			fmt.Println("sql ", sql)
			panic(err.Error())
		}
		var data float64
		for results.Next() {
			err = results.Scan(&data)
			if err != nil {
				panic(err.Error())
				fmt.Println("ERROR scan ", err)
				continue
			}

			break
		}
		fmt.Println("data", data, targetNumArr[i], data - targetNumArr[i])
		delayArr = append(delayArr, int(data - targetNumArr[i]))
	}
	fmt.Println("targetNumArr", targetNumArr)

	return delayArr

}

func changeData2(){

	sqlArr := []string{
		//"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-01-01' and createdAt < '2020-02-01' limit %d",
		//"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-02-01' and createdAt < '2020-03-01' limit %d offset %d",
		//"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-03-01' and createdAt < '2020-04-01' limit %d offset %d",
		//"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-04-01' and createdAt < '2020-05-01' limit %d offset %d",
		//"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-05-01' and createdAt < '2020-06-01' limit %d offset %d",
		//"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-06-01' and createdAt < '2020-07-01' limit %d offset %d",

		"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-07-01' and createdAt < '2020-08-01' and platformCommission>1.1 limit %d offset %d",
		"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-08-01' and createdAt < '2020-09-01' and platformCommission>1.1 limit %d offset %d",
		"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-09-01' and createdAt < '2020-10-01' and platformCommission>1.1 limit %d offset %d",
		"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-10-01' and createdAt < '2020-11-01' and platformCommission>1.1 limit %d offset %d",
		"SELECT id FROM india_round_rummy WHERE createdAt >= '2020-11-01' and createdAt < '2020-12-01' and platformCommission>1.1 limit %d offset %d",
	}
	//差值
	//[780.75 678.9199999999837 2787.9489999997895 2275.8310000002384 2254.520999999717 2263.4599999999627 4.5803916e+06 1.1466688e+07 2.15097453e+06 1.9418017e+06 1.92735817e+06]
	//[0.7400000000488944 19.510000000009313 69.44899999978952 39.93099999986589 16.321000000461936 18.259999999776483
	//2254.731000000611 5760.815999999642 22937.091000000015 55221.22999999998 51880.741000000155]


	delayNumArr := []int{
		//1,
		//19,
		//69,
		//39,
		//16,
		//18, //6月

		2254,
		5760,
		22937,
		55221,
		51880,
	}
	idArr := []int{}
	for i, sqlStr := range sqlArr {
		if delayNumArr[i] == 0 {
			continue
		}
		offNum := RandInts(500, 5000)
		sql := fmt.Sprintf(sqlStr, delayNumArr[i], offNum)
		results, err := database.Query(sql)
		fmt.Println("sql ", sql)
		if err != nil {
			fmt.Println("sql ", sql)
			panic(err.Error())
		}
		var id int
		count := 0
		for results.Next() {
			err = results.Scan(&id)
			if err != nil {
				panic(err.Error())
				fmt.Println("ERROR scan ", err)
				continue
			}
			idArr = append(idArr, id)
			count = count + 1
		}
		results.Close()
		fmt.Println("id", id, count)
	}
	fmt.Println("idArr", len(idArr))
	//id=8256010
	for i, id := range idArr {
		sql := fmt.Sprintf("update india_round_rummy set platformCommission=platformCommission-1 where id=%d and platformCommission>1", id)
		results, err := database.Query(sql)
		if err != nil {
			fmt.Printf("writeRummyData ERROR sql:%v, err:%+v \n", sql, err)
			return
		}
		results.Close()
		fmt.Println(sql, i)
	}

}

//检查每天的差额
func checkVeryDate() {

	fmt.Println("insertData")
	//准备读取文件
	fileName := "data.csv"
	fs, err := os.Open(fileName)
	if err != nil {
		log.Fatalf("can not open the file, err is %+v", err)
	}
	defer fs.Close()
	r := csv.NewReader(fs)

	//针对大文件，一行一行的读取文件
	var  allPlatformCommission float64
	//for i:=0; i<4; i++ {
	for i := 0; ; i++ {
		row, err := r.Read()
		if err != nil && err != io.EOF {
			log.Fatalf("can not read, err is %+v", err)
		}
		if err == io.EOF {
			break
		}
		if i < 2 {
			continue
		}
		fmt.Printf("[day: %v, %v] %v\n", i-1, row[0], row[1])

		dateStr := row[0]
		chargeStr := row[1]
		chargeNum, _ := strconv.ParseFloat(chargeStr,2)
		if chargeNum <= 0 {
			continue
		}
		if dateStr == "2020/1/1"{
			break
		}

		dateStr1 := dateStr + " 00:00:00"
		dateStr2 := dateStr + " 23:59:59"
		sql := fmt.Sprintf("select sum(platformCommission) from india_round_rummy where createdAt >= '%s' and createdAt <= '%s'", dateStr1, dateStr2)
		fmt.Println("sql ", sql)
		results, err := database.Query(sql)
		if err != nil {
			fmt.Printf("checkVeryDate ERROR sql:%v, err:%+v \n", sql, err)
			return
		}
		var data float64
		for results.Next() {
			err = results.Scan(&data)
			if err != nil {
				panic(err.Error())
				fmt.Println("ERROR scan ", err)
				continue
			}
			break
		}
		results.Close()
		allPlatformCommission = allPlatformCommission + data
		delayNum := int(data) - int(chargeNum)
		if delayNum == 0 {
			continue
		}

		idArr := []int{}
		//大于0 或小于0
		fmt.Println("date delay:", delayNum)
		sql = fmt.Sprintf("SELECT id FROM india_round_rummy WHERE createdAt >= '%s' and createdAt < '%s'  limit %d ", dateStr1, dateStr2, int(math.Abs(float64(delayNum))))
		if delayNum > 0 {
			sql = fmt.Sprintf("SELECT id FROM india_round_rummy WHERE createdAt >= '%s' and createdAt < '%s' and platformCommission>1.01 limit %d ", dateStr1, dateStr2, int(math.Abs(float64(delayNum)) * 1 ))
		}
		results, err = database.Query(sql)
		//fmt.Println("sql ", sql)
		if err != nil {
			fmt.Println("sql ", sql)
			panic(err.Error())
		}
		var id int
		count := 0
		for results.Next() {
			err = results.Scan(&id)
			if err != nil {
				panic(err.Error())
				fmt.Println("ERROR scan ", err)
				continue
			}
			idArr = append(idArr, id)
			count = count + 1
		}
		results.Close()
		fmt.Println("idArr", len(idArr))
		if len(idArr) == 0 {
			continue
		}
		//对指定id 进行 platformCommission + -
		for _, id := range idArr {
			if delayNum > 0 {
				//-1
				sql = fmt.Sprintf("update india_round_rummy set platformCommission=platformCommission-1 where id=%d", id)
			}else if delayNum < 0 {
				//+1
				sql = fmt.Sprintf("update india_round_rummy set platformCommission=platformCommission+1 where id=%d", id)
			}
			results, err := database.Query(sql)
			if err != nil {
				fmt.Printf("writeRummyData ERROR sql:%v, err:%+v \n", sql, err)
				return
			}
			results.Close()

			//fmt.Println(sql, i)
		}



	}
	fmt.Println("allPlatformCommission", allPlatformCommission)



}





func main() {
	fmt.Println("main start: ", time.Now())
	initMysql()
	testFunc()


	//插入数据
	//insertData()

	//changeData()
	//changeData2()

	//checkVeryDate()

	if database != nil {
		defer database.Close()
	}
	fmt.Println("main end: ", time.Now())
}